package com.ccteam.fluidmusic.ui.local.artist

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentLocalArtistDetailBinding
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.utils.generateContainerTransform
import com.ccteam.fluidmusic.widget.AppBarStateChangeListener
import com.ccteam.shared.result.artist.ArtistListItem
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import jp.wasabeef.glide.transformations.BlurTransformation

@AndroidEntryPoint
class LocalArtistDetailFragment : Fragment() {

    private var _binding: FragmentLocalArtistDetailBinding? = null
    private val binding get() = _binding!!

    private val screenWidth: Int by lazy {
        resources.displayMetrics.widthPixels
    }

    private lateinit var parentId: String

    private val args: LocalArtistDetailFragmentArgs by navArgs()

    private val artistDetailViewModel: LocalArtistDetailViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
        // 设置共享动画
        sharedElementEnterTransition = generateContainerTransform(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLocalArtistDetailBinding.inflate(inflater,container,false)
        // 设置AppbarLayout的高度（为屏幕宽度）
        binding.collapseToolbarArtistDetail.layoutParams.apply {
            height = screenWidth
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        postponeEnterTransition()
        view.doOnPreDraw {
            startPostponedEnterTransition()
        }

        binding.toolbarArtistDetail.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        parentId = args.fluidmusicParentId

        // 设置歌手相关信息内容
        updateArtistInfo(args.artistInfo)

        binding.appbarArtistDetail.addOnOffsetChangedListener(object: AppBarStateChangeListener(){
            override fun onOffsetChanged(appBarLayout: AppBarLayout) {
            }

            override fun onStateChanged(appBarLayout: AppBarLayout, state: Int) {
                // 当处于折叠状态时，我们将不显示的透明度变为0
                // 当重新展开时，再将其显示
                if(state == COLLAPSED){
                    binding.ivArtistPhoto.animate().alpha(0f).setDuration(175).start()
                    binding.artistInfoContainer.animate().alpha(0f).setDuration(175).start()
                } else {
                    binding.ivArtistPhoto.animate().alpha(1f).setDuration(175).start()
                    binding.artistInfoContainer.animate().alpha(1f).setDuration(175).start()
                }
            }

        })

        artistDetailViewModel.artistDetailParentIds.observe(viewLifecycleOwner, {
            if(it.isNotEmpty()){
                if(binding.viewpagerArtistDetail.adapter == null){
                    binding.viewpagerArtistDetail.adapter = ArtistDetailPagerAdapter(it,this)
                }
                TabLayoutMediator(binding.tabArtistDetail,
                    binding.viewpagerArtistDetail){ tab, position ->
                    tab.text = it[position].second
                }.attach()
            }
        })
    }

    private fun updateArtistInfo(artistInfo: ArtistListItem) = with(binding){
        Glide.with(this@LocalArtistDetailFragment)
            .load(artistInfo.artistPhoto)
            .placeholder(R.drawable.img_default_album)
            .into(binding.ivArtistPhoto)
        // 高斯模糊的图片，放在清晰图片上方，但图片大小不能太大，否则会导致高斯模糊效果不佳
        Glide.with(this@LocalArtistDetailFragment)
            .load(artistInfo.artistPhoto)
            .placeholder(R.drawable.img_default_album)
            .override(100,100)
            .apply(RequestOptions.bitmapTransform(BlurTransformation(25)))
            .into(binding.ivArtistPhotoBlur)

        toolbarArtistDetail.title = artistInfo.artistName
        artistInfo.subtitle?.let {
            tvArtistInfo.text = getString(R.string.description_artist_detail_info,it.trackNum,it.albumNum)
        }
    }

    class ArtistDetailPagerAdapter(private val parentIds: List<Pair<String,String>>,
                                   fragment: Fragment): FragmentStateAdapter(fragment) {

        override fun getItemCount(): Int = parentIds.size

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> LocalArtistDetailMusicPagerFragment.newInstance(parentIds[position].first)
                1 -> LocalArtistDetailAlbumPagerFragment.newInstance(parentIds[position].first)
                else ->
                    throw IllegalArgumentException("错误的布局参数")
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}